#include "../source/server.hpp"

#include <iostream>
#include <time.h>
// #include <stdlib.h> // atoi 函数需要的头文件

using namespace std;

uint64_t conn_id = 0;
std::unordered_map<uint64_t, PtrConnection> _conns;
EventLoop baseloop;
std::vector<LoopThread> threads(2); // 创建2个从属线程
int next_loop = 0;

void ConnectionDestroy(const PtrConnection &conn)
{
    _conns.erase(conn->Id());
}

void OnConnected(const PtrConnection &conn)
{
    DBG_LOG("NEW CONNECTION:%p", conn.get());
}

void OnMessage(const PtrConnection &conn, Buffer *buf)
{
    DBG_LOG("%s", buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "Hello World";
    conn->Send(str.c_str(), str.size());

    // conn->Shutdown(); // 测试 server 接收一次数据就中断 client
}

void NewConnection(int fd)
{
    conn_id++;

    next_loop = (next_loop + 1) % 2;

    PtrConnection conn(new Connection(threads[next_loop].GetLoop(), conn_id, fd));
    // 为新的通信套接字设置可读事件的回调函数
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRelease(10); // 启动非活跃超时销毁
    conn->Established();             // 就绪初始化
    _conns.insert(std::make_pair(conn_id, conn));

    DBG_LOG("new ------------------");
}

int main(void)
{
    // base_loop 对应的线程在 reactor模型里面充当的是主线程(注意 reactor模型也是可以没有从属线程的)
    Acceptor acceptor(&baseloop, 8500);
    DBG_LOG("baseloop");
    // 回调中，获取新连接，并未新连接创建Channel，并添加监控
    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));
    // 注意 baseloop 得开启监听功能的哦，其实就是开启 baseloop 的可读事件(就是获取新连接功能)
    acceptor.Listen();

    baseloop.Start();

    return 0;
}
